#!/usr/bin/python3
# coding=utf-8
# 录制输入，包括录制按键和鼠标

from pynput.mouse import Listener
from pynput.mouse import Button, Controller
import win32gui, win32ui, win32con, win32api
import csv
import threading
import time
recode = []
# mouse_is_down = False
def _do_stc(x, y):
	'''
	将捕获的屏幕坐标，转换成当前活动窗口的相对坐标
	'''
	hwnd = win32gui.GetForegroundWindow()
	
	title = ""
	title = win32gui.GetWindowText(hwnd)
	print("hwnd %d title %s" %(hwnd, title))
	if hwnd:
	  cx, cy =  win32gui.ScreenToClient(hwnd, (x, y))
	else:
	  cx, cy = x, y
	# return title, cx, cy
	return title, x, y

def _check_down(recode):
	'''
	从后往前找到第一个鼠标消息类型是down一行数据
	'''
	index = 0
	for i, row in enumerate(reversed(recode)):
		print(row)
		if row[5] == 'down':
		  index = i
		  break;
	return -1 - index

def on_move(x, y):
	global mouse_is_down
	title, rx, ry = _do_stc(x, y)

	# if mouse_is_down == True:
	# 	recode.append([title, rx, ry, x, y , "move"])
	recode.append([title, rx, ry, x, y , "move"])
	
	  
def on_click(x, y, button, pressed):
	# global mouse_is_down
	
	title, rx, ry = _do_stc(x, y)

	mouse_is_down = True
	if (button == Button.right):
		return False
	if (pressed == True):
		recode.append([title, rx, ry, x, y, "down"])
		# mouse_is_down = True
	else:
		index = _check_down(recode)
		unuse, last_rx, last_ry = _do_stc(recode[index][3], recode[index][4])
		recode[index][0], recode[index][1], recode[index][2]  = title, last_rx, last_ry
		recode.append([title, rx, ry, x, y, "up"])
		# mouse_is_down = False

	  

def on_scroll(x, y, dx, dy):
	title, x, y = _do_stc(x, y)

def recode_csv(recode, fname="unname.csv"):
	wo = open(fname, 'w', encoding="utf-8")
	w_csv = csv.writer(wo)
	w_csv.writerow(["wintitle", "rel-x","rel-y", "x", "y","mouse-action"])
	w_csv.writerows(recode);
	wo.close()

def _thread_record():
	with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
		listener.join()


	recode_csv(recode)
	
def mouse_record():
	t = threading.Thread(target=_thread_record)
	t.start()
	

if __name__ == '__main__':
	_thread_record()